<template>
  <div>
    <van-nav-bar title="商品修改" left-text="返回" left-arrow @click-left="leftClick" />
    <upload-pic @iconChange="iconChange" :showIcon="form.icon"></upload-pic>
    <van-cell-group>
      <van-field v-model="form.name" label="商品名称" clearable v-validate="'required'" data-vv-name="商品名称"
        :error-message="errors.first('商品名称')" placeholder="请输入商品名称" required maxLength="12" />
      <van-field v-model="form.price" label="商品价格" clearable v-validate="'required|price'" data-vv-name="商品价格"
        :error-message="errors.first('商品价格')" placeholder="请输入商品价格" required />

      <van-field v-model="form.stock" label="库存" clearable v-validate="'required'" data-vv-name="库存"
        :error-message="errors.first('库存')" placeholder="请输入库存" required />
        
      <van-field v-model="form.description" label="商品详情" clearable v-validate="'required'" data-vv-name="商品详情"
        :error-message="errors.first('商品详情')" type="textarea" required />
    </van-cell-group>
    <van-cell title="爬楼费">
      <van-checkbox v-model="deliver" shape="square"></van-checkbox>
    </van-cell>
    <van-button class="bottom-btn" size="large" type="info" @click="save">保存</van-button>
  </div>
</template>

<script>
  import {
    PRODUCT_DETAIL,
    PRODUCT_EDIT
  } from '@/api/product'
  import UploadPic from '@/components/UploadPic'
  export default {
    components: {
      UploadPic
    },
    data() {
      return {
        form: {},
        deliver: false
      }
    },
    mounted() {
      this.getDetail();
    },
    methods: {
      leftClick() {
        this.$router.go(-1)
      },
      //获取详情
      getDetail() {
        this.$reqGet(PRODUCT_DETAIL, {
          productId: this.$route.params.id,
          own: this.$route.params.own
        }).then(res => {
          let info = res.data.sProduct;
          this.form = info;
          this.deliver = info.deliver ? true : false
        });
      },
      //保存
      save() {
        if(!this.form.icon){
          this.$toast('请选择图片');
          return;
        }
        this.form.deliver = this.deliver ? 1 : 0
        this.$validator.validateAll().then((result) => {
          if (result) {
            this.$reqPost(PRODUCT_EDIT, this.form).then(res => {
              this.$toast('修改成功');
              this.$router.go(-1);
            }).catch(err => {
              this.$toast('修改失败');
            });
          }
        });
      },
      iconChange(val) {
        this.form.icon = val;
      }
    }
  }

</script>
